package com.itheima.web.servlet;

import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet(urlPatterns = "/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {
            request.setCharacterEncoding("utf-8");
            //获取输入的验证码
            String verifycode = request.getParameter("verifycode");
            //获取图形验证码
            HttpSession session = request.getSession();
            String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
            // 为了确保验证码是一次性的,获取以后需要从session中移除
            session.removeAttribute("CHECKCODE_SERVER");
            if (!verifycode.equalsIgnoreCase(checkcode_server)) {
                request.setAttribute("msg", "验证码输入有误");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
                return;
            }
            // 两码一致,验证码校验通过了. 校验用户名和密码
            //5. 获取所有请求参数
            Map<String, String[]> map = request.getParameterMap();
            User user = new User();
            //6. 封装到User对象中
            BeanUtils.populate(user, map);
            //7. 调用service查询
            UserService userService = new UserServiceImpl();
            User uu = userService.login(user);

            //8. 判断返回的User对象是否为空
            if (uu == null) {
                request.setAttribute("msg", "用户名或密码有误");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
                return;
            }
            //9. 用户名或密码正确
            //9.1 保存用户信息到session域中
            session.setAttribute("user", uu.getUsername());
            response.sendRedirect(request.getContextPath() + "/success.jsp");
        }   catch (Exception e) {
              e.printStackTrace();
        }

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}